﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XjjXmm.Infrastructure.User;

namespace xjjxmm.infrastructure.EventChannel
{
    /// <summary>
    /// 发布者
    /// </summary>
   /* public interface IPublish
    {
        string EventType { get; set; }

        dynamic Data { get; set; }
    }*/

    /// <summary>
    /// 订阅者
    /// </summary>
    public interface ISubscriber
    {
        Task Receive(dynamic? data = null);
    }

    /// <summary>
    /// 事件总线
    /// </summary>
    /*    public interface IEventChannel
        {
            void Add(string eventType, ISubscriber suscriber);

            void Remove(string eventType, ISubscriber suscriber);

            Task Notify(string eventType, dynamic data);
        }*/


    /// <summary>
    /// 事件总线
    /// </summary>
    public class EventDispatcher
    {
        private Dictionary<string, List<ISubscriber>> dict = new();

        private EventDispatcher() { }

        private static readonly EventDispatcher dispatcher = new EventDispatcher();

        public static EventDispatcher Instance { get { return dispatcher; } }

        public void Register(string eventType, ISubscriber suscriber)
        {
            if (!dict.ContainsKey(eventType))
            {
                dict.Add(eventType, new List<ISubscriber>());
            }

            dict[eventType].Add(suscriber);
        }

        public async Task Emit(string eventType, dynamic? data = null)
        {
            foreach (var item in dict[eventType])
            {
                await item.Receive(data);
            }
        }

        public void Unregister(string eventType, ISubscriber suscriber)
        {
            if (dict.ContainsKey(eventType))
            {
                dict[eventType].Remove(suscriber);
            }
        }

        public void Clear(string eventType)
        {
            if (dict.ContainsKey(eventType))
            {
                dict[eventType].Clear();
            }
        }

        public void Clear()
        {
            foreach (var item in dict)
            {
                item.Value.Clear();
            }

            dict = new Dictionary<string, List<ISubscriber>>();
        }
    }
}
